package com.simpou.commons.utils.validation;

import com.simpou.commons.utils.behavior.Validator;
import com.simpou.commons.utils.exception.model.RuleViolation;
import com.simpou.commons.utils.string.RegexHelper;
import static com.simpou.commons.utils.validation.IPValidator.isValid;

import lombok.AllArgsConstructor;
import lombok.Getter;

import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * Validador de e-mail.
 *
 * @author Jonas Pereira
 * @since 2011-06-25
 * @version 2012-07-29
 */
public final class EmailValidator implements Validator<String> {
    /**
     * Pattern.
     */
    private static final Pattern PATTERN = Pattern.compile(RegexHelper.EMAIL);

    /**
     * @param value Valor a ser validado.
     * @return Null se valor válido.
     */
    public static RuleViolation isValid(final String value) {
        final RuleViolation violation;

        if ((value == null) || value.isEmpty()) {
            violation = null;
        } else if (value.length() < 5) {
            violation = Violation.INVALID_LENGTH;
        } else {
            final Matcher m = PATTERN.matcher(value);

            if (m.matches()) {
                violation = null;
            } else {
                violation = Violation.NOT_MATCH;
            }
        }

        return violation;
    }

    /**
     * @param email E-mail a ser validado.
     */
    @Override
    public RuleViolation validate(final String email) {
        return isValid(email);
    }
    @Getter
    @AllArgsConstructor
    public enum Violation implements RuleViolation {
        
        NOT_MATCH("E-mail doesnt match " + RegexHelper.EMAIL),
        INVALID_LENGTH("Email must have at least 5 characters.");

        private String msg;

        @Override
        public String getType() {
            return this.name();
        }
    }
}
